package com.redsoil.house.ui.capital.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.ListHolder;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.redsoil.house.R;
import com.redsoil.house.app.AppContext;
import com.redsoil.house.base.RootFragment;
import com.redsoil.house.model.bean.CountAssetVO;
import com.redsoil.house.model.bean.DictListVO;
import com.redsoil.house.model.bean.ReceiptListVO;
import com.redsoil.house.model.bean.TestVO;
import com.redsoil.house.model.http.api.ApiConstants;
import com.redsoil.house.model.http.download.ApiHttpManager;
import com.redsoil.house.model.http.download.DownloadFileInterface;
import com.redsoil.house.ui.capital.activity.PdfActivity;
import com.redsoil.house.ui.capital.contract.CapitalInfoContract;
import com.redsoil.house.ui.capital.presenter.CapitalInfoPresenter;
import com.redsoil.house.ui.news.adapter.NewsTitleAdapter;
import com.redsoil.house.ui.remit.activity.RemitActivity;
import com.redsoil.house.utils.FileOpenUtils;
import com.redsoil.house.utils.Util;
import com.redsoil.house.widget.HomeRemitItem;
import com.redsoil.house.widget.actionbar.NewsTopBar;
import com.weidingqiang.rxfiflibrary2.app.AppConstants;
import com.zhy.autolayout.AutoLinearLayout;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnMoreItemPickListener;
import cn.addapp.pickers.picker.LinkagePicker;

/**
 * 资产信息
 */
public class CapitalInfoFragment extends RootFragment<CapitalInfoPresenter> implements CapitalInfoContract.View {

    @BindView(R.id.remit_button)
    Button remit_button;

    @BindView(R.id.pieChart)
    PieChart pieChart;

    @BindView(R.id.totalMoney_tv)
    TextView totalMoney_tv;

    @BindView(R.id.totalZZC_tv)
    TextView totalZZC_tv;

    @BindView(R.id.balance_tv)
    TextView balance_tv;

    @BindView(R.id.totalReceipts_tv)
    TextView totalReceipts_tv;

    @BindView(R.id.homeRemitItem1)
    HomeRemitItem homeRemitItem1;

    @BindView(R.id.homeRemitItem2)
    HomeRemitItem homeRemitItem2;

    @BindView(R.id.homeRemitItem3)
    HomeRemitItem homeRemitItem3;

    @BindView(R.id.homeRemitItem4)
    HomeRemitItem homeRemitItem4;

    @BindView(R.id.line_1)
    View line_1;
    @BindView(R.id.line_2)
    View line_2;
    @BindView(R.id.line_3)
    View line_3;
    @BindView(R.id.line_4)
    View line_4;

    private List<HomeRemitItem> list;
    private List<View> views;

    @BindView(R.id.remit_layout)
    AutoLinearLayout remit_layout;

    @BindView(R.id.totalBuyJPrice_tv)
    TextView totalBuyJPrice_tv;

    @BindView(R.id.money_type_tv)
    TextView money_type_tv;

    private DialogPlus filterDialog;

    private NewsTitleAdapter newsTitleAdapter;

    private List<DictListVO.DataListBean> moneys;

    private String[] years;

    private String[] months;

    private String[] quarters;

    public static CapitalInfoFragment newInstance() {
        Bundle args = new Bundle();

        CapitalInfoFragment fragment = new CapitalInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick(R.id.remit_button)
    void onRemitButton(){
        startActivity(RemitActivity.newInstance(getContext()));
    }

    @Override
    protected void initEventAndData() {
        super.initEventAndData();
        stateLoading();

        list = new ArrayList<HomeRemitItem>();
        list.add(homeRemitItem1);
        list.add(homeRemitItem2);
        list.add(homeRemitItem3);
        list.add(homeRemitItem4);

        views = new ArrayList<View>();
        views.add(line_1);
        views.add(line_2);
        views.add(line_3);
        views.add(line_4);

        mPresenter.getMainData();

        years = new String[]{"2023","2022","2021","2020","2019","2018","2017","2016","2015","2014","2013","2012","2011"};
        months = new String[]{"一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
        quarters = new String[]{"第一季度","第二季度","第三季度","第四季度"};
    }

    @Override
    public void postReceiptListSuccess(ReceiptListVO receiptListVO) {

//        if (receiptListVO.getDataList().size() == 0)
//        {
////            remit_layout.setVisibility(View.GONE);
//        }

        for (int k=0;k<views.size();k++){
            View view = views.get(k);
            view.setVisibility(View.GONE);
        }

        for(int i=0;i<Math.min(list.size(),receiptListVO.getDataList().size());i++){
            ReceiptListVO.DataListBean bean =  receiptListVO.getDataList().get(i);
            HomeRemitItem homeRemitItem = list.get(i);
            View view = views.get(i);
            homeRemitItem.setData(bean);
            homeRemitItem.setVisibility(View.VISIBLE);
            view.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void countAssetSuccess(CountAssetVO countAssetVO) {

        totalMoney_tv.setText(AppContext.getInstance().getCurrentMoneyType()+Util.nfValue(countAssetVO.getTotalMoney()));
//        totalMoney_tv.setText(AppContext.getInstance().getMoneySymbol()+"123456789012");

        totalZZC_tv.setText(Util.nfValue(countAssetVO.getTotalZZC()));
        balance_tv.setText(Util.nfValue(countAssetVO.getBalance()));
        totalReceipts_tv.setText(Util.nfValue(countAssetVO.getTotalReceipts()));

        String str;
        if(AppContext.getInstance().getCurrentMoneyType().equals("JPY")){
            str ="¥"+Util.nfValue(countAssetVO.getTotalBuyJPrice());
        }else {
            str ="¥"+Util.nfValue(countAssetVO.getTotalBuyJPrice())+"<br/>("+AppContext.getInstance().getCurrentMoneyType()
                    +Util.nfValue(countAssetVO.getTotalBuyPrice())+")";
        }

        totalBuyJPrice_tv.setText(Html.fromHtml(str));


        List<PieEntry> strings = new ArrayList<>();
        strings.add(new PieEntry((float)countAssetVO.getTotalZZC(),""));
        strings.add(new PieEntry((float) countAssetVO.getBalance(),""));
        strings.add(new PieEntry((float) countAssetVO.getTotalReceipts(),""));

        PieDataSet dataSet = new PieDataSet(strings,"Label");

        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(getResources().getColor(R.color.orangec74));
        colors.add(getResources().getColor(R.color.blue1fc));
        colors.add(getResources().getColor(R.color.gray2a2));
        dataSet.setColors(colors);

        PieData pieData = new PieData(dataSet);
        pieData.setDrawValues(false);

        //描述
        Description description = new Description();
        description.setText("");
        pieChart.setDescription(description);

        pieChart.setHoleRadius(83);
        pieChart.setHoleColor(R.color.black029);

        pieChart.setHighlightPerTapEnabled(false);
        pieChart.setRotationEnabled(false);

        pieChart.setData(pieData);
        pieChart.invalidate();

        Legend legend = pieChart.getLegend();
        legend.setEnabled(false);

    }

    @OnClick(R.id.money_type_tv)
    void onMoneyClick(){
        if (filterDialog == null) {

            newsTitleAdapter = new NewsTitleAdapter(getContext(),moneys);

            filterDialog = DialogPlus.newDialog(getContext())
                    .setGravity(Gravity.BOTTOM)
                    .setContentHolder(new ListHolder())
                    .setAdapter(newsTitleAdapter)
                    .setCancelable(true)//设置不可取消   可以取消
                    .setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                            DictListVO.DataListBean bean = moneys.get(position);
                            if(!money_type_tv.getText().equals(bean.getValue())){
                                money_type_tv.setText(bean.getValue());
                                AppContext.getInstance().setCurrentMoneyType(bean.getCode());
                                AppContext.getInstance().setMoneySymbol(bean.getDesc().split(",")[1]);
//                                stateLoading();

                                mPresenter.getCountAsset(bean.getCode());
                                mPresenter.postReceiptList();
                            }
                            dialog.dismiss();
                        }
                    })
                    .create();

        }

        filterDialog.show();
    }

    @OnClick(R.id.rent_detail_tv)
    void onRentDetail(){
        LinkagePicker.DataProvider provider = new LinkagePicker.DataProvider() {

            @Override
            public boolean isOnlyTwo() {
                return true;
            }

            @Override
            public List<String> provideFirstData() {
                ArrayList<String> firstList = new ArrayList<>();
                firstList.add("年");
                firstList.add("月");
                firstList.add("季度");
                return firstList;
            }

            @Override
            public List<String> provideSecondData(int firstIndex) {
                ArrayList<String> secondList = new ArrayList<>();
                switch (firstIndex){
                    case 0:
                        List<String> yearList = Arrays.asList(years);
                        secondList.addAll(yearList);
                        break;
                    case 1:
                        List<String> monthList = Arrays.asList(months);
                        secondList.addAll(monthList);
                        break;
                    case 2:
                        List<String> quarterList = Arrays.asList(quarters);
                        secondList.addAll(quarterList);
                        break;
                }
                return secondList;
            }

            @Override
            public List<String> provideThirdData(int firstIndex, int secondIndex) {
                return null;
            }

        };
        LinkagePicker picker = new LinkagePicker(getActivity(), provider);
        picker.setCanLoop(false);
//        picker.setLabel("小时制", "点");
//        picker.setSelectedIndex(0, 8);
        //picker.setSelectedItem("12", "9");
        picker.setOnMoreItemPickListener(new OnMoreItemPickListener<String>() {

            @Override
            public void onItemPicked(String first, String second, String third) {
                switch (first){
                    case "年":
                        mPresenter.exportEarnings("1",second);
                        break;
                    case "月":
                        mPresenter.exportEarnings("2",String.valueOf(getIndex(months,second)));
                        break;
                    case "季度":
                        mPresenter.exportEarnings("3",String.valueOf(getIndex(quarters,second)));
                        break;
                }
            }
        });
        picker.show();
    }

    public int getIndex(String[] arr, String value) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].equals(value)) {
                return i+1;                  //字符串时，换为 equals
            }
        }
        return -1;//如果未找到返回-1
    }

    @Override
    public void exportEarningSuccess(String data) {
        ToastUtils.showLongToast("正在打开文件,请稍后..");
        String[] filepath = data.split("/");

        //1.开始下载文件
        ApiHttpManager.getManager().downloadAudioFile(data, AppConstants.RECORD_DOWNLOAD_PATH+filepath[filepath.length-1], new DownloadFileInterface() {

            @Override
            public void onSuccess(String filePath) {
                startActivity(PdfActivity.newInstance(getContext(),filePath));
//                FileOpenUtils.openFile(getContext(),filePath);
            }

            @Override
            public void onFailure(String des) {
                //3.文件下载失败
                ToastUtils.showShortToast("网络连接超时");
//                downloadDialog.dismiss();
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
//                downtextview.setText("正在下载 " + bytesWritten + " / " + totalSize);
//                arcProgress.setProgress((int) ((bytesWritten * 100) / totalSize));
            }
        });
    }

    @Override
    public void getComplete() {
        stateMain();
    }

    @Override
    public void responeError(String errorMsg) {
//        stateError();
        ToastUtils.showShortToast("数据加载失败");
    }

    @Override
    public void getDicListSuccess(DictListVO dictListVO) {
        moneys = dictListVO.getDataList();
        AppContext.getInstance().setMoneys(dictListVO.getDataList());
    }

//

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_capital_info;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }
}
